﻿using EmoneyWeiXinCommon;
using mymemcached2014;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using EmoneyWeiXinEntity;
using EmoneyWeiXinBLL;
using System.Data;

namespace EmoneyWeiXin.Controllers
{
    public class GetDataFileController : Controller
    {


        string server1 = "172.28.1.210:11211,172.28.1.211:11211";  //停盘，复盘相关个股

        string server2 = "172.28.5.57:11211";  //沪指，深成指主力资金流入流出数据   

        string server3 = "172.28.20.12:11211";  //前3大涨跌幅板块主力资金流入流出数据


        // longhubang 龙虎榜   
        //  zdqsbk 前3大涨跌幅板块主力资金流入流出数据
        // zjlx   沪指，深成指主力资金流入流出数据
        // tpfp   当天停牌、复牌个股
        public ActionResult Index()
        {

            if (Request["type"] == "longhubang")
            {
                return Content(GetLonghuBang());
            }
            else if (Request["type"] == "zdqsbk")
            {

                return Content(QSDZDFLRLC());
            }
            else if (Request["type"] == "tpfp")
            {
                return Content(GetJrTpFp());
            }
            else if (Request["type"] == "zjlx")
            {
                return Content(GetFzSzLrLc());
            }
            return Content("0");
        }


        #region  获取停盘复盘数据

        class RootData
        {
            public List<TpFpDataMain> root { get; set; }
        }

        class TpFpDataMain
        {
            public List<TpFpData> suspended_stocks_test { get; set; }
        }

        class TpFpData
        {
            public string s { get; set; }
            public DateTime st { get; set; }
            public DateTime rt { get; set; }
            public string n { get; set; }
            public string m { get; set; }
            public string d { get; set; }
            public string i { get; set; }
        }
        /// <summary>
        /// 获取今日停盘复牌的数据
        /// </summary>
        /// <returns></returns>
        public string GetJrTpFp()
        {
            try
            {
                MyMemcachedTools210 mm = new MyMemcachedTools210();
                byte[] bs = mm.Get("suspendstocks");
                string json = System.Text.Encoding.GetEncoding("utf-8").GetString(bs);
                RootData obj = JsonTools.ToObject<RootData>(json);
                StringBuilder sb = new StringBuilder("");  //用来装停牌数据

                StringBuilder sb2 = new StringBuilder();  //用来装复牌数据

                foreach (TpFpData item in obj.root[0].suspended_stocks_test)
                {
                    if (item.d.Contains("停牌") && item.st != null && (item.st - System.DateTime.Now).Days == 0)
                    {
                        sb.Append(string.Format(@"<div style='background-color: #e4e1e1; margin-bottom: 10px; padding: 5px; border: 1px solid gray'>
                                                    <div style='font-weight: bold;'>{0} &nbsp;{1}</div>
                                                    <div style='margin-top: 6px'>{2}</div>
                                                  </div>", item.s, item.n, item.i));
                    }
                    else if (item.d.Contains("复牌"))
                    {
                        sb2.Append(string.Format(@"<div style='background-color:#f39e72; margin-bottom: 10px; padding: 5px; border: 1px solid red'>
                                       <div style='font-weight: bold;color:red'>{0} &nbsp;{1}</div>
                                       <div style='margin-top: 6px;color:red'>{2}</div>
                                     </div>", item.s, item.n, item.i));
                    }
                }

                string html = "<div style='color: red; text-align: center; font-weight: bold; font-size: 25px'>停牌个股</div>";
                html += sb.ToString();
                html += "<div style='color: red; text-align: center; font-weight: bold; font-size: 25px'>复牌个股</div>";
                html += sb2.ToString();
                SaveToDb("tpfp", "今日停牌复牌", "今日停牌复牌", html, "http://static.emoney.cn/webupload/JiaQunTwoCode/2015/12/5b874862-5a0b-4817-b218-f80182edcfe2.jpg");
            }
            catch (Exception)
            {
                return "0";

            }

            return "1";
        }
        #endregion

        #region 获取沪指深指主力资金流入流出数据

        public class GzSzLrLc
        {
            public string C { get; set; } //股票代码
            public string N { get; set; } //股票名称
            public double V { get; set; }//成交量
            public double A { get; set; }//成交额
            public double J { get; set; }//资金流向
            public float BT { get; set; } //大单比率
            public string TT { get; set; } //行情日期
        }

        public string GetFzSzLrLc()
        {
            MyMemcachedTools57 mm57 = new MyMemcachedTools57();

            string temp = @"<div style='border: 1px solid #ff6a00;margin-bottom:10px'>
    <div style='background-color: #ff6a00; color: white; line-height: 25px; text-align: center; font-weight: bold'>{0}</div>
    <table style='width: 100%'>
        <tr>
            <td>资金流向：</td>
            <td>{1}</td>
        </tr>
    </table>
</div>

";

            #region 沪指
            byte[] bs = mm57.Get("EMONEY_DATA_1.0_QUOTES_0000001");
            string json = System.Text.Encoding.GetEncoding("gb2312").GetString(bs);
            GzSzLrLc obj = JsonTools.ToObject<GzSzLrLc>(json.Replace("[", "").Replace("]", ""));
            string html = string.Format(temp, obj.N, (obj.J / 100000000).ToString("0.0") + "亿");
            #endregion

            #region 深指
            bs = mm57.Get("EMONEY_DATA_1.0_QUOTES_1399001");
            json = System.Text.Encoding.GetEncoding("gb2312").GetString(bs);
            obj = JsonTools.ToObject<GzSzLrLc>(json.Replace("[", "").Replace("]", ""));
            html += string.Format(temp, obj.N, (obj.J / 100000000).ToString("0.0") + "亿");
            #endregion

            #region 创业板块
            bs = mm57.Get("EMONEY_DATA_1.0_QUOTES_1399006");
            json = System.Text.Encoding.GetEncoding("gb2312").GetString(bs);
            obj = JsonTools.ToObject<GzSzLrLc>(json.Replace("[", "").Replace("]", ""));
            html += string.Format(temp, obj.N, (obj.J / 100000000).ToString("0.0") + "亿");
            #endregion

            SaveToDb("zjlx", "资金流向", "资金流向", html, "http://static.emoney.cn/webupload/JiaQunTwoCode/2015/12/454a546d-8a44-4af5-bcef-d51134cdebc5.jpg");

            return "1";
        }

        #endregion

        #region  获取前3打涨跌幅板块
        public class ZDFLRLC
        {
            public string N { get; set; }
            public string C { get; set; }
            public string NewC { get; set; }
            public string F { get; set; }
            public string F5 { get; set; }
            public double J { get; set; }
            public string SZJ { get; set; }
            public string XDJ { get; set; }
            public string QS { get; set; }
            public string RS { get; set; }
        }

        public string QSDZDFLRLC()
        {
            MyMemcachedTools12 mmtools = new MyMemcachedTools12();

            string temp = @"<div style='border: 1px solid #ff6a00;margin-bottom:10px'>
    <div style='background-color: #ff6a00; color: white; line-height: 25px; text-align: center; font-weight: bold'>{0}</div>
    <table style='width: 100%'>
        <tr>
            <td>板块名称</td>
            <td>{1}</td>
            <td>资金流向：</td>
            <td>{2}</td>
        </tr>

         <tr>
            <td>板块名称</td>
            <td>{3}</td>
            <td>资金流向：</td>
            <td>{4}</td>
        </tr>
         <tr>
            <td>板块名称</td>
            <td>{5}</td>
       
            <td>资金流向：</td>
            <td>{6}</td>
        </tr>
    </table>
</div>
";
            string html = "";
            #region 涨幅前三
            byte[] bs = mmtools.Get("EMONEY_SDD_TOP_ZDF_GROUP_HY");
            string json = System.Text.Encoding.GetEncoding("gb2312").GetString(bs);
            List<ZDFLRLC> lst = JsonTools.ToObject<List<ZDFLRLC>>(json);
            html += string.Format(temp, "涨幅前三", lst[0].N, (lst[0].J / 100000000).ToString("0.0") + "亿", lst[1].N, (lst[1].J / 100000000).ToString("0.0") + "亿", lst[2].N, (lst[2].J / 100000000).ToString("0.0") + "亿"); ;

            #endregion

            #region 跌幅前三
            bs = mmtools.Get("EMONEY_SDD_BOTTOM_ZDF_GROUP_HY");
            json = System.Text.Encoding.GetEncoding("gb2312").GetString(bs);
            lst = JsonTools.ToObject<List<ZDFLRLC>>(json);
            html += string.Format(temp, "跌幅前三", lst[0].N, (lst[0].J / 100000000).ToString("0.0") + "亿", lst[1].N, (lst[1].J / 100000000).ToString("0.0") + "亿", lst[2].N, (lst[2].J / 100000000).ToString("0.0") + "亿");
            #endregion

            SaveToDb("zdqsbk", "前3大涨跌幅板块主力资金流入流出数据", "前3大涨跌幅板块主力资金流入流出数据", html, "http://static.emoney.cn/webupload/JiaQunTwoCode/2015/12/454a546d-8a44-4af5-bcef-d51134cdebc5.jpg");

            return "1";
        }
        #endregion

        #region 龙虎榜数据
        public string GetLonghuBang()
        {


            string template = @"<div style='border: 1px solid #ff6a00;margin-bottom:10px;'>
    <div style='background-color: #ff6a00; color: white; line-height: 25px; text-align: center'>{0}&nbsp;{1}</div>
    <div style='padding: 4px;'>
        <table width='100%' style='border: 1px solid  #e2a571'>
            {[temp001]}
        </table>
        <div style='text-align: center; background: #e2a571'>总共买入{2}万</div>
    </div>
    <div style='padding: 4px;'>
        <table width='100%' style='border: 1px solid  #e2a571'>
            {[temp003]}
        </table>
        <div style='text-align: center; background: #e2a571'>总共卖出{3}万</div>
    </div>
</div>

";

            StringBuilder sb = new StringBuilder();
            DataTable dt = CreateReportByModelBLL.GetLongHubang();
            string currentStock = "";
            double sum = 0;
            double fsum = 0;
            StringBuilder tempTr = new StringBuilder();
            StringBuilder tempTr2 = new StringBuilder();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                double tempSum = Convert.ToDouble(dr["jmSum"]);
                if (tempSum > 0)
                {
                    sum += tempSum;
                    tempTr.Append("<tr><td title='" + dr["SalesDepartName"] + "'>" + MySubString(dr["SalesDepartName"].ToString(), 10) + "</td><td>买入</td><td>" + (tempSum / 10000).ToString("0.0") + "万</td></tr>");
                }
                else
                {
                    fsum += tempSum;
                    tempTr2.Append("<tr><td title='" + dr["SalesDepartName"] + "'>" + MySubString(dr["SalesDepartName"].ToString(), 10) + "</td><td>卖出</td><td>" + (tempSum / 10000).ToString("0.0") + "万</td></tr>");
                }


                if (dr["secuCode"].ToString() != currentStock || i == dt.Rows.Count - 1)
                {
                    if (i != 0)
                    {

                        sb.Append(string.Format(template.Replace("{[temp001]}", tempTr.ToString()).Replace("{[temp003]}", tempTr2.ToString()), dr["secubrief"], dr["secuCode"], (sum / 10000).ToString("0.0"), (fsum / 10000).ToString("0.0")));
                        currentStock = dr["secuCode"].ToString();
                        sum = 0;
                        fsum = 0;
                        tempTr = new StringBuilder();
                        tempTr2 = new StringBuilder();
                    }

                }

            }

            string htmlSum = sb.ToString();
            SaveToDb("longhubang", "龙虎榜", "龙虎榜机构席位买卖情况", htmlSum, "http://static.emoney.cn/webupload/JiaQunTwoCode/2015/12/7ecac485-44dc-42df-b971-5aa4b1cbb669.jpg");
            return "1";

        }

        string MySubString(string str, int len)
        {
            if (str.Length > len)
            {
                return str.Substring(0, len) + "...";
            }
            return str;
        }

        #endregion


        private bool SaveToDb(string typeName, string title, string summary, string content, string imgUrl = "")
        {
            try
            {
                NewsReportfbEntity news = new NewsReportfbEntity();
                news.Author = "autoCreater";
                news.Content = content;
                news.createtime = System.DateTime.Now;
                news.ImageUrl = imgUrl;
                news.isvalid = 1;
                news.keyword = typeName;
                news.MemuType = typeName;
                news.mtitle = title;
                news.Nature = "";
                news.newguid = System.Guid.NewGuid().ToString();
                news.PubMethod = "好股";
                news.PubStatus = 1;
                news.remark = "";
                news.title = title;
                news.Summary = summary;
                news.updatetime = System.DateTime.Now;
                NewsReportManager.UpdateNewsReportfb(news);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

    }





}
